﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;

namespace Nature.Core.Cache
{
    public class DefaultCacheStrategy : BaseCacheStrategy
    {
        private readonly MemoryCache _mc;


        public DefaultCacheStrategy(string cacheGroupName, TimeSpan interval)
            : base(cacheGroupName, interval)
        {
            _mc = new MemoryCache(cacheGroupName);
        }

        public override void Set(string key, object value)
        {
            var cp = new CacheItemPolicy();
            DateTime now = DateTime.Now;
            cp.SlidingExpiration = Interval;
            _mc.Set(key, value, cp);
        }

        public override void Set(string key, object value, DateTime expiryTime)
        {
            _mc.Set(key, value, new DateTimeOffset(expiryTime));
        }

        public override object Get(string key)
        {
            return _mc.Get(key);
        }

        public override IList<object> FindAll()
        {
            return _mc.Select(p => p.Value).ToList();
        }

        public override void Remove(string key)
        {
            _mc.Remove(key);
        }

        public override void RemoveAll()
        {
            _mc.Dispose();
        }
    }
}
